package com.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.common.BaseResponse;
import com.study.common.ErrorCode;
import com.study.exception.BusinessException;
import com.study.pojo.User;
import com.study.pojo.request.UserLoginRequest;
import com.study.pojo.request.UserRegisterRequest;
import com.study.service.UserService;
import com.study.utils.ResultUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.study.contant.UserConstant.ADMIN_ROLE;
import static com.study.contant.UserConstant.USER_LOGIN_STATE;

/**
 * Controller：请求/控制层，即不做任何业务处理，只接受请求。
 * 应用程序的入口点，负责接受用户的请求并返回响应，调用Service层的方法来处理业务逻辑，
 * 并将结果返回给前端用户。
 * 用户接口
 * @author fruity
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if(userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userPassword = userRegisterRequest.getUserPassword();
        String userAccount = userRegisterRequest.getUserAccount();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        //对参数本身的校验
        if(StringUtils.isAnyBlank(userPassword, userAccount, checkPassword)){
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        //return new BaseResponse<>(0,res,"ok");
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest , HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        //对参数本身的校验
        if(StringUtils.isAnyBlank(userPassword, userAccount)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if(request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/select")
    public BaseResponse<List<User>> selectUser(String username ,HttpServletRequest request) {
        //判断是否为管理员
        if(iaAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //判断用户名是否为空
        if(StringUtils.isNotBlank(username))
            //如果不写参数默认模糊查询
            queryWrapper.like("username", username);
        //返回脱敏后的用户信息
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id ,HttpServletRequest request) {
        if(iaAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if(id  <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 是否为管理员
     * @param request
     * @return
     */
    private boolean iaAdmin(HttpServletRequest request){
        //权限校验，仅管理员可执行
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if(user == null || user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return true;
    }
}
